package com.fh.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import utils.JwtUtil;
import utils.ResultCode;
import utils.ResultObj;
import java.nio.charset.StandardCharsets;

@Component
public class GateWayFilter implements GlobalFilter, Ordered {
    @Autowired
    private FilterIgnoreUrl filterIgnoreUrl;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();//通过请求获得路径
        AntPathMatcher pathMatcher = new AntPathMatcher();
        for (String url : filterIgnoreUrl.getUrls()) {
            if (pathMatcher.match(url,path)){//拿请求中的路径和放开的请求进行比较
                return chain.filter(exchange);//放开的请求
            }
        }
        String token = request.getHeaders().getFirst("Authorization-token");
        if(StrUtil.isBlank(token)){
            return responseData(exchange,ResultObj.error(ResultCode.LOGIN_DISABLED));
        }
        ResultObj claimsFromToken = JwtUtil.getClaimsFromToken(token);
        if(claimsFromToken.getCode()!=200)
        {
            return responseData(exchange,ResultObj.error(ResultCode.LOGIN_DISABLED));
        }
        //通过Token 获取到用户的手机号放到request中
        String phone = JwtUtil.getPhoneFromToken(token);
        request.mutate().headers(httpHeaders -> {
            httpHeaders.add("phone",phone);
            httpHeaders.add("token",token);
        });
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
    private Mono responseData(ServerWebExchange exchange, ResultObj resultObj){
        ServerHttpResponse response=exchange.getResponse();
        String data= JSONUtil.toJsonStr(resultObj);
        DataBuffer dataBuffer=response.bufferFactory().allocateBuffer()
                .write(data.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(dataBuffer));
    }
}
